package com.three.work.serviceImpl;

import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.three.work.bean.*;
import com.three.work.controller.helper.$;
import com.three.work.mapper.SignMapper;
import com.three.work.service.AppuserService;
import com.three.work.service.OutputPriceService;
import com.three.work.service.SignService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.three.work.bean.result.ResultPage;
import com.three.work.controller.model.ApiResultModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2020-04-02
 */
@Service
@Slf4j
public class SignServiceImpl extends ServiceImpl<SignMapper, Sign> implements SignService {
    /**
     * 添加Sign
     *
     * @param sign 前端传进的参数
     * @return 返回统一信息
     */
    @Override
    public ApiResultModel addSign(Sign sign) {
        if (this.save(sign)) {
            return $.success();
        } else {
            return $.error("添加失败");
        }
    }

    /**
     * 编辑跳转页面的回显数据Sign
     *
     * @param id 前端传进的参数
     * @return 返回实体类
     */
    @Override
    public Sign selectSignByIdSign(Integer id) {
        return this.getById(id);
    }


    /**
     * 编辑Sign
     *
     * @param sign 前端传进的参数
     * @return 返回统一信息
     */
    @Override
    public ApiResultModel editSign(Sign sign) {
        if (this.updateById(sign)) {
            return $.success();
        } else {
            return $.error("编辑失败");
        }
    }

    /**
     * 删除一条Sign
     *
     * @param id 前端传进的ID
     * @return 返回统一信息
     */
    @Override
    public ApiResultModel delSign(Integer id) {
        if (this.removeById(id)) {
            return $.success();
        } else {
            return $.error("删除失败");
        }
    }

    @Autowired
    AppuserService appuserService;

    @Override
    public ApiResultModel statisticsSign(String time, Integer type) {
        //总人数
        int userCount = appuserService.count();
        List<SignReslut> signs = new ArrayList<>();
        switch (type) {
            case 1:   //年月日 签到统计
                signs.add(setReslutDay(time, userCount, 0));
                signs.add(setReslutDay(time, userCount, 1));
                return $.success(signs);
            case 2:
                signs.add(setReslutMeoth(time, userCount, 0));
                signs.add(setReslutMeoth(time, userCount, 1));
                return $.success(signs);
            case 3:
                signs.add(setReslutWeek(time, userCount, 0));
                signs.add(setReslutWeek(time, userCount, 1));
                return $.success(signs);
            default:
                return $.error("类型不正确");
        }
    }

    private SignReslut setReslutDay(String time, int userCount, int isPm) {
        DateTime dateTime= DateUtil.parse(time);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("m",dateTime.toString("MM"));
        wrapper.eq("d",dateTime.toString("dd"));
        wrapper.eq("y",dateTime.toString("yyyy"));
        wrapper.eq("isPm", isPm);
        int pm = count(wrapper);//上午
        SignReslut signReslut = new SignReslut();
        signReslut.setTime(time);
        signReslut.setIsPm(isPm);
        signReslut.setCountPeopleNum(userCount);
        signReslut.setSignPeopleNum(pm);
        return signReslut;
    }

    private SignReslut setReslutMeoth(String time, int userCount, int isPm) {
         DateTime dateTime= DateUtil.parse(time,"yyyy-MM");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("m",dateTime.toString("MM"));
        wrapper.eq("y",dateTime.toString("yyyy"));
        wrapper.eq("isPm", isPm);
        int pm = count(wrapper);//上午
        SignReslut signReslut = new SignReslut();
        signReslut.setTime(time);
        signReslut.setIsPm(isPm);
        signReslut.setCountPeopleNum(userCount);
        signReslut.setSignPeopleNum(pm);
        return signReslut;
    }

    private SignReslut setReslutWeek(String time, int userCount, int isPm) {
        QueryWrapper wrapper = new QueryWrapper();
        DateTime dateTime= DateUtil.parse(time,"yyyy-MM-dd" );
        List<Date> days = dateToWeek(dateTime);
        for (Date date : days) {
           String y=DateUtil.format(date,"yyyy");
           String m=DateUtil.format(date,"MM");
           String d=DateUtil.format(date,"dd");
            wrapper.eq("y", y);
            wrapper.eq("m", m);
            wrapper.eq("d", d);
            wrapper.eq("isPm", isPm);
            wrapper.or();
        }

        int pm = count(wrapper);//上午
        SignReslut signReslut = new SignReslut();
        signReslut.setTime(time);
        signReslut.setIsPm(isPm);
        signReslut.setCountPeopleNum(userCount);
        signReslut.setSignPeopleNum(pm);
        return signReslut;
    }

    public static void main(String[] args) {


    }
    public static List<Date> dateToWeek(Date mdate) {
        int b = mdate.getDay();
        Date fdate;
        List<Date> list = new ArrayList<Date>();
        Long fTime = mdate.getTime() - b * 24 * 3600000;
        for (int a = 1; a <= 7; a++) {
            fdate = new Date();
            fdate.setTime(fTime + (a * 24 * 3600000));
            list.add(a-1, fdate);
        }
        return list;
    }

    @Autowired
    OutputPriceService outputPriceService;
    /**
     * 分页查询Sign
     *
     * @param page  页码
     * @param limit 查几条
     * @param sign  前端传进的参数
     * @return 返回统一分页信息
     */
    @Override
    public ResultPage findSignByPage(Integer page, Integer limit, Sign sign) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("page", (page - 1) * limit);
        paramMap.put("limit", limit);
        paramMap.put("sign", sign);
     List<OutputPrice>   outputPrices=  outputPriceService.list();

        List<Sign> list = baseMapper.selectMyPage(paramMap);
        for (int i = 0; i < list.size(); i++) {
            Sign signDataBase=list.get(i);
            for (int j = 0; j < outputPrices.size(); j++) {
                OutputPrice outputPrice=outputPrices.get(j);
                String  localName=signDataBase.getLocationName();
                if(localName!=null){
                    try{
                        localName=JSONObject.parseObject(localName).get("address").toString();
                    }catch (Exception e){

                    }

                }else{
                    localName="";
                }
                System.out.println(localName);
                if(StrUtil.startWithAny(localName,outputPrice.getLocationName())){
                    signDataBase.setPrice(  outputPrice.getPrice().toString());
                };
            }
        }


        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<Sign> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    @Override
    public ResultPage signManage(Integer page, Integer limit, String time) {
        DateTime dateTime= DateUtil.parse(time,"yyyy-MM");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("page", (page - 1) * limit);
        paramMap.put("limit", limit);
        paramMap.put("y", dateTime.toString("yyyy"));
        paramMap.put("m", dateTime.toString("MM"));
        List<SignManageResult> list = baseMapper.selectSignManage(paramMap);
        Integer count = baseMapper.countSignManage(paramMap);
        ResultPage<SignManageResult> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    @Override
    public ResultPage statisticsSignByUser(Integer page, Integer limit, String time, Integer userId) {
        ResultPage<UserSignInfo> resultPage = new ResultPage<>();
        if(StrUtil.isBlank(time)||userId==null){
            resultPage.setCode(500);
            resultPage.setCount(0);
            resultPage.setMsg("失败，请检查参数");
            resultPage.setData(null);
        }

        DateTime dateTime= DateUtil.parse(time,"yyyy-MM");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("page", (page - 1) * limit);
        paramMap.put("limit", limit);
        paramMap.put("y", dateTime.toString("yyyy"));
        paramMap.put("m", dateTime.toString("MM"));
        paramMap.put("userId", userId);
        List<UserSignInfo> list = baseMapper.selectStatisticsSignByUser(paramMap);
        Integer count = baseMapper.countStatisticsSignByUser(paramMap);

        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }
    @Override
    public ApiResultModel signInfoByUser(  String time, Integer userId) {
        DateTime dateTime= DateUtil.parse(time,"yyyy-MM-dd");
         QueryWrapper queryWrapper=new QueryWrapper();
         queryWrapper.eq("y", dateTime.toString("yyyy"));
         queryWrapper.eq("m", dateTime.toString("MM"));
         queryWrapper.eq("d", dateTime.toString("dd"));
         queryWrapper.eq("user_id",userId);
         return  $.success(list(queryWrapper));
    }
    @Override
    public ApiResultModel FindInsertSign(String id, String amPm, String y, String m, String d, String state) {

        Integer userId=Integer.valueOf(id);
        Integer isPm=Integer.valueOf(amPm);


        Integer row;
        if(state.equals("0")){
            row=baseMapper.getCountSign(userId,isPm,y,m,d);
            if(row.equals(1)){
                row=baseMapper.deleteByIdSign(userId,isPm,y,m,d);
                return $.success("删除了这次签到");
            }
            return  $.success("没有查询到这次签到");
        }

        if(state.equals("1")){
            row=baseMapper.getCountSign(userId,isPm,y,m,d);
            if(row.equals(0)){
                row=baseMapper.insertSign(userId,isPm,y,m,d);
                return $.success("插入成功");
            }
            return  $.success("这个签到已经存在");
        }

        return $.error("state参数错误 0/1");
    }
}
